<?php


namespace app\api\controller;

use app\common\service\ElevenLabService;
use think\response\Json;
use think\facade\Request;

class ElevenLabsController extends ApiBaseController
{
    /**
     * 上传语音
     * @param ElevenLabService $service
     * @return Json
     */
    public function addVoice(ElevenLabService $service): Json{
        try {
            $files = Request::file('files');
            if (empty($files)){
                throw new \Exception('参数错误，上传音频文件不能为空。');
            }
            if (empty($this->param['name'])){

                throw new \Exception('参数错误，name不能为空。');
            }

            $this->param['user_id'] = $this->user->id;
            return api_success($service->addVoice($this->param,$files),true);
        }catch (\Exception $e){
            return api_error($e->getMessage());
        }
    }

    /**
     * 获取语音列表接口，仅返回用户上传的语音列表
     * @param ElevenLabService $service
     * @return Json
     */
    public function voices(ElevenLabService $service): Json{

        try {
            $this->param['user_id'] = $this->user->id;
            return api_success($service->getVoices($this->param));
        }catch (\Exception $e){
            return api_error($e->getMessage());
        }
    }

    /**
     * 文字转语音
     * @param ElevenLabService $service
     * @return Json
     */
    public function textToSpeech(ElevenLabService $service): Json{

        try {
            if (empty($this->param['voice_id'])){
                throw new \Exception('参数错误，voice_id不能为空。');
            }
            if (empty($this->param['text'])){

                throw new \Exception('参数错误，text不能为空。');
            }

            $service->textToSpeech($this->param);
            return api_success(['创建成功']);
        }catch (\Exception $e){
            return api_error($e->getMessage());
        }
    }

    /**
     * @param ElevenLabService $service
     * 获取文字转语音历史列表
     * @return Json
     */
    public function history(ElevenLabService $service): Json{

        try {
            $data = json_decode($service->history($this->param,$this->limit),true);
            return api_success($data);
        }catch (\Exception $e){
            return api_error($e->getMessage());
        }
    }
}